package cn.wolfcode.job;

import cn.wolfcode.common.web.Result;
import cn.wolfcode.domain.SeckillProductVo;
import cn.wolfcode.feign.SeckillProductFeignApi;
import cn.wolfcode.redis.SeckillRedisKey;
import com.alibaba.fastjson.JSON;
import com.dangdang.ddframe.job.api.ShardingContext;
import com.dangdang.ddframe.job.api.simple.SimpleJob;
import lombok.Getter;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @author hkj
 * @email 1349091387@qq.com
 * @date 2021/12/30
 * 源码允许修改，并且本人十分乐意有 大佬 来对代码进行 随 意 调 教
 **/
@Component
@RefreshScope
@Slf4j
@Getter@Setter
public class InitSeckillProductJob implements SimpleJob {
    @Value("${jobCron.initSeckillProduct}")
    private String cron;

    @Autowired
    private SeckillProductFeignApi seckillProductFeign;
    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 创建一个定时任务，用于将秒杀和商品信息数据查询出来后存入redis中
     * @param shardingContext
     */
    @Override
    public void execute(ShardingContext shardingContext) {
        //System.out.println(shardingContext.getShardingParameter() + "==>" + shardingContext.getShardingItem());
        dowork(shardingContext.getShardingParameter());
    }

    private void dowork(String time) {
        //远程调用秒杀服务
        Result<List<SeckillProductVo>> seckillProducts = seckillProductFeign.seckillProducts(time);
        /**
         * result值有几种情况
         * 1.如果调用服务挂掉了，直接走降级方法，方法中返回null
         * 2.调用服务出现了异常，被统一异常处理到
         * 3. 正常返回数据 List<SeckillProductVo>
         */
        //将查询出来的秒杀数据存入redis中,通过hash的结构将数据存入
        if (seckillProducts != null && !seckillProducts.hasError()){
            List<SeckillProductVo> seckillProductVos = seckillProducts.getData();
            if(seckillProductVos != null && seckillProductVos.size() > 0){
                for (SeckillProductVo seckillProductVo : seckillProductVos) {
                    redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_PRODUCT_LIST.getRealKey(time),seckillProductVo.getId() + "", JSON.toJSONString(seckillProductVo));
                    //将库存数量也存入redis中
                    redisTemplate.opsForHash().put(SeckillRedisKey.SECKILL_STOCK_COUNT_HASH.getRealKey(time),seckillProductVo.getId() + "",seckillProductVo.getStockCount() + "");
                }
                System.out.println("同步数据：" + time);
            }
        }
    }
}
